Writing Functions
12 February, 2024
You already….
Please install and load the following packages
Access lecture slide from the course landing page
I am Ayush.
I am a researcher working at the intersection of data, law, development and economics.
I teach Data Science using R at Gokhale Institute of Politics and Economics
I am a RStudio (Posit) certified tidyverse Instructor.
I am a Researcher at Oxford Poverty and Human development Initiative (OPHI), at the University of Oxford.
Reach me
ayush.ap58@gmail.com
ayush.patel@gipe.ac.in
0.837636mutate() functionfunction() and specify the argument x, then wrap up your argument and specify the operation inside {}myfirstfunction <- function(x){0.837636 * x}
data %>%
mutate(new_a = myfirstfunction(a),
new_b = myfirstfunction(b),
new_c = myfirstfunction(c),
new_d = myfirstfunction(d)) id a b c d new_a new_b new_c new_d
1 h 5 1 32 19 4.188180 0.837636 26.80435 15.91508
2 h 6 2 33 20 5.025816 1.675272 27.64199 16.75272
3 i 7 3 34 21 5.863452 2.512908 28.47962 17.59036
4 i 8 4 35 22 6.701088 3.350544 29.31726 18.42799
5 j 9 5 36 23 7.538724 4.188180 30.15490 19.26563
6 j 10 6 37 24 8.376360 5.025816 30.99253 20.10326
data, you want to multiply 2 to an even number, or keep the number as it is if odddatadata, multiply 1.77364 to all numeric variables by writing a functiondatadata where you want to group the variables by id and get the mean of numeric variables{{ }}my_eda_function <- function(dataframe, variable) {
dataframe %>%
summarize(
count = n(),
minimum_value = min({{ variable}}, na.rm = TRUE),
maximum_value = max({{ variable}}, na.rm = TRUE),
range = max({{ variable}}, na.rm = TRUE) - min({{ variable}}, na.rm = TRUE)
)
}
my_eda_function(data,a) count minimum_value maximum_value range
1 6 5 10 5
ChickWeight data from datasets, create your own summary function that gives the minimum, maximum and range of the weight variablediet and gives the weightdiamonds dataset from ggplot2binwidth can be avoidedbinwidth while writing the function?diamonds dataset, write a function for making a bar graph, and then using the function, plot cut and colorx and y using it